package SERVLET;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import BO.AutorBO;
import BO.ObraBO;
import DTO.AutorDTO;
import DTO.ObraDTO;
import UTIL.UploadUtil;

public class AutorServlet extends HttpServlet {

	private ObraBO obraBO = new ObraBO();
    private AutorBO autorBO = new AutorBO();        
	private AutorDTO autorDTO = new AutorDTO();    
    private boolean incluindo;
    private boolean alterando;            
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-control", "no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "Fri, 25 Dec 1980 00:00:00 GMT");        
        
        if (request.getParameter("acao") != null) {
            if (request.getParameter("acao").equals("Novo Autor")) {
            	novo(request, response);
            } else if (request.getParameter("acao").equals("Editar")) {
                editar(request, response);
            } else if (request.getParameter("acao").equals("Visualizar")){
            	visualizar(request, response);
            } else if(request.getParameter("acao").equals("Pesquisar")){            	
            	pesquisar(request, response);
            } else if (request.getParameter("acao").equals("Excluir")) {
                excluir(request, response);
            } else if (request.getParameter("acao").equals("Incluir")) {
                incluir(request, response);         
            } else if (request.getParameter("acao").equals("showImg")) {
            	if(request.getParameter("id") != null &&
            			autorBO.pesquisarPorCodigo(Long.parseLong(request.getParameter("id"))).getImagem() != null) {
	            	response.setContentType("image/jpg");
	        		try{
	        			OutputStream outputStream  = response.getOutputStream();
	        			outputStream.write(autorBO.pesquisarPorCodigo(Long.parseLong(request.getParameter("id"))).getImagem());
	        			outputStream.flush();
	        			outputStream.close();
	        		} catch (Exception e) { e.printStackTrace(); }
            	}
            } else {
            	if(request.getSession().getAttribute("redirecionar") != null){
                	String redirecionar = (String) request.getSession().getAttribute("redirecionar");
                	request.getSession().removeAttribute("redirecionar");        
                	if(redirecionar.equals("retornarObra")){
                		request.getRequestDispatcher(HomeServlet.paginas.get("obraIncluirAlterar")).forward(request, response);
                	} else {
                		request.getRequestDispatcher(HomeServlet.paginas.get("colecaoIncluirAlterar")).forward(request, response);
                	}
                } else {            	
                	redicionarPesquisarRemoverAtributo(request, response);
                }
            }
        }
    }
       
    private void novo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	autorDTO = new AutorDTO();            	
        request.getSession().setAttribute("autorDTO", autorDTO);
        setIncluindo(true);
        setAlterando(false);
        redicionarIncluirAlterarRemoverAtributo(request, response);
    }
    
    private void pesquisar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	autorDTO.setNome(request.getParameter("pesquisa"));
    	request.getSession().setAttribute("autores", autorBO.pesquisarPorNome(autorDTO));       	                 	            	
        redicionarPesquisar(request, response);
    }
    
    private void editar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	autorDTO.setCodigo(Long.parseLong(request.getParameter("id")));
        autorDTO = autorBO.pesquisarPorCodigo(autorDTO.getCodigo());
        request.getSession().setAttribute("autorDTO", autorDTO);
        setAlterando(true);
        setIncluindo(false);
        redicionarIncluirAlterarRemoverAtributo(request, response);
    }       
    
    private void excluir(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	autorDTO.setCodigo(Long.parseLong(request.getParameter("id")));
        autorDTO = autorBO.pesquisarPorCodigo(autorDTO.getCodigo());
        if (!autorBO.remover(autorDTO)) {
            request.getSession().setAttribute("erro", "Erro ao realizar exclusão.");            
            redicionarPesquisar(request, response);            
        } else{
        	request.getSession().setAttribute("autores", autorBO.pesquisarTodos());
        	redicionarPesquisarRemoverAtributo(request, response);            
        }               
    }    
    
    private void incluir(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	String oldOne = autorDTO.getNome();                
        criarObjeto(request);                               
        String redirecionar = "";                
        if(request.getSession().getAttribute("redirecionar") != null){
        	redirecionar = (String) request.getSession().getAttribute("redirecionar");
        	request.getSession().removeAttribute("redirecionar");        
        	incluindo = true;
        }
        if (!autorBO.existe(autorDTO) || (isAlterando() && autorDTO.getNome().equals(oldOne))) {
            if (isIncluindo() ? autorBO.incluir(autorDTO) : isAlterando() ? autorBO.alterar(autorDTO) : false) {                        
                alterando = incluindo = false;                        
                if(!redirecionar.equals("")){
                	request.getSession().removeAttribute("redirecionar");     
                	request.getSession().setAttribute("autores", autorBO.naoPesquisarAutoresDaObra((ObraDTO)  request.getSession().getAttribute("obraDTO")));                	
                	if(redirecionar.equals("retornarObra")){
                		request.getRequestDispatcher(HomeServlet.paginas.get("obraIncluirAlterar")).forward(request, response);
                	} else {
                		request.getRequestDispatcher(HomeServlet.paginas.get("colecaoIncluirAlterar")).forward(request, response);
                	}
                } else {
                	request.getSession().setAttribute("autores", autorBO.pesquisarTodos());
                	redicionarPesquisarRemoverAtributo(request, response);
                }
            }
        } else {
            autorDTO.setNome(oldOne);
            request.getSession().setAttribute("erro", "Autor já existe.");
            redicionarIncluirAlterar(request, response);
        }                       
    }
    
    private void visualizar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	autorDTO.setCodigo(Long.parseLong(request.getParameter("id")));
        autorDTO = autorBO.pesquisarPorCodigo(autorDTO.getCodigo());
        request.getSession().setAttribute("autorDTO", autorDTO);
        request.getSession().setAttribute("livrosDoAutor", obraBO.pesquisarObrasDoAutor(autorDTO));
        setAlterando(false);
        setIncluindo(false);
        redicionarVisualizar(request, response);
    }
    
    private void redicionarPesquisarRemoverAtributo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getSession().removeAttribute("erro");
        redicionarPesquisar(request, response);
    }
       
    private void redicionarIncluirAlterarRemoverAtributo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        removerAtributo(request);
        redicionarIncluirAlterar(request, response);
    }
    
    private void removerAtributo(HttpServletRequest request){
        request.getSession().removeAttribute("erro");
    }
        
    private void redicionarPesquisar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{    	
        request.getRequestDispatcher(HomeServlet.paginas.get("autorPesquisar")).forward(request, response);
    }
    
    private void redicionarIncluirAlterar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{    	
        request.getRequestDispatcher(HomeServlet.paginas.get("autorIncluirAlterar")).forward(request, response);
    }
    
    private void redicionarVisualizar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{    	
        request.getRequestDispatcher(HomeServlet.paginas.get("autorVisualizar")).forward(request, response);
    }
    
    private void criarObjeto(HttpServletRequest request) {    	        
        autorDTO.setNome(request.getParameter("nome"));
        autorDTO.setDescricao(request.getParameter("descricao"));
        
        UploadUtil upl = new UploadUtil();
        upl.doFilePost(request, request.getServletContext());
        autorDTO.setImagem(upl.getImg());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
       
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

    public boolean isIncluindo() {
        return incluindo;
    }

    public void setIncluindo(boolean incluindo) {
        this.incluindo = incluindo;
    }

    public boolean isAlterando() {
        return alterando;
    }

    public void setAlterando(boolean alterando) {
        this.alterando = alterando;
    }
}